package com.example.administrator.shzs.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.utils.ToastUtils;
import com.example.administrator.shzs.activity.BaseActivity;
import com.example.administrator.shzs.adapter.GoodsOrderAdapter;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.db.GoodsBean;
import com.example.administrator.shzs.db.GoodsDataBaseInterface;
import com.example.administrator.shzs.db.OperateGoodsDataBase;
import com.example.administrator.shzs.entity.OrderData;
import com.example.administrator.shzs.entity.OrderdModel;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 订单页面
 */
public class OrderActivity extends BaseActivity implements View.OnClickListener {


    @Bind(R.id.tv_name)
    TextView tvName;//收货人
    @Bind(R.id.tv_address)
    TextView tvAddress;//地址
    @Bind(R.id.tv_phone)
    TextView tvPhone;//电话
    @Bind(R.id.tv_please_select_address)
    TextView tvPleaseSelectAddress;

    @Bind(R.id.ll_select_address)
    LinearLayout llSelectAddress;//点击跳转地址页面

    @Bind(R.id.tv_shop_name)
    TextView tvShopName;//商家名

    @Bind(R.id.tv_total_price)
    TextView tvTotalPrice;//总计
    @Bind(R.id.tv_net_pay)
    TextView tvNetPay;//实付
    @Bind(R.id.tv_stay_pay)
    TextView tvStayPay;//待支付

    @Bind(R.id.rl_remark)
    RelativeLayout rlRemark;//备注点击布局
    @Bind(R.id.tv_remark)
    TextView tvRemark;//备注文本

    @Bind(R.id.rl_bottom)
    RelativeLayout rlBottom;//提交订单

    @Bind(R.id.lv_order)
    RecyclerView mRecyclerOrder;//商品列表

    @Bind(R.id.btn_submit_order)
    Button btnSubmitOrder;
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_sendfree)
    TextView tvSendfree;//配送费
    @Bind(R.id.tv_pake)
    TextView tvPake; //打包费

    private String tRemark; //接收备注
    private String Pake; //接收打包费

    private GoodsOrderAdapter oldAdapter;

    private List<GoodsBean> goodsBeans;

    private GoodsDataBaseInterface mGoodsDataBaseInterface;


    /**
     * 商家店名
     */
    private String shopName;

    private String shopImage;

    /**
     * 商家Id
     */
    private String shopId;


    /**
     * 用户Id
     */
    private String userId;

    /**
     * 收货地址
     */
    private String address;

    /**
     * 收货电话
     */
    private String phone;

    /**
     * 收货人姓名
     */
    private String name;

    /**
     * 备注
     */
    private String remark;//商品口味备注

    /**
     * 配送费
     */
    private String sendfree;

    /**
     * 纬度
     */
    private double latitude;

    /**
     * 经度
     */
    private double longitude;
    /**
     * 当前时间
     */
    private String currentTime;

    private SimpleDateFormat sdf;
    private Date data;

    /**
     * 所有商品总价
     */
    private double priceAll;

    private OrderData orderData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);
        ButterKnife.bind(this);
        MyApplication.app.activityList.add(this);
        mGoodsDataBaseInterface = OperateGoodsDataBase.getInstance();

        setViews();
        //获取商家数据
        getShopData();

        setData();
        setAdapter();
        setListeners();

    }

    //布局管理器
    private void setViews() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayout.VERTICAL);
        mRecyclerOrder.setLayoutManager(manager);
    }

    //注册点击事件
    private void setListeners() {

        rlRemark.setOnClickListener(this);
        llSelectAddress.setOnClickListener(this);
        btnSubmitOrder.setOnClickListener(this);
        ivBack.setOnClickListener(this);
    }

    private void setData() {

//        获取数据
        userId = MyApplication.app.getUserId();
        latitude = MyApplication.app.getLatitude();
        longitude = MyApplication.app.getLongitude();


        //        获取当前时间
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        data = new Date(System.currentTimeMillis());
        currentTime = sdf.format(data);

        //购物车所有商品总价
        priceAll = mGoodsDataBaseInterface.getGoodsPriceAll(this, Integer.parseInt(shopId));
        priceAll = priceAll + Double.parseDouble(Pake) + Double.parseDouble(sendfree);
        tvNetPay.setText("¥" +priceAll + "");//实付
        tvTotalPrice.setText(priceAll + "");//总计
        tvStayPay.setText("¥" +priceAll + "");//待支付
        tvShopName.setText(shopName);//商家名
        tvPake.setText("¥" + Pake);//打包费
        //配送费
        tvSendfree.setText("¥" + sendfree);

    }

    private void setAdapter() {

        oldAdapter = new GoodsOrderAdapter(this, goodsBeans);
        mRecyclerOrder.setAdapter(oldAdapter);

    }


    /**
     * 获取商家数据
     */
    private void getShopData() {

        Intent intent = getIntent();
        shopImage = intent.getStringExtra("shopImage");
        shopName = intent.getStringExtra("shopName");
        shopId = intent.getStringExtra("shopId");
        Pake = intent.getStringExtra("PackageFree");
        sendfree = intent.getStringExtra("sendfree");

        DbUtils db = DbUtils.create(this);
        try {
            //获取购物车中商家所有商品数据
            goodsBeans = db.findAll(Selector.from(GoodsBean.class).where("shopid", "=", shopId));

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    /**
     * 选择地址
     */
    private static final int SELECT_ADDRESS = 1;

    /**
     * 备注
     */
    private static final int REMARK = 2;

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.ll_select_address://选择地址

                Intent address = new Intent(this, ShippingAddressActivity.class);
                address.putExtra("selectAddress", true);
                startActivityForResult(address, SELECT_ADDRESS);
                //返回动画
//                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_in_left);
                break;

            case R.id.rl_remark://备注

                Intent remark = new Intent(this, RemarkActivity.class);
                startActivityForResult(remark, REMARK);
//                overridePendingTransition(R.anim.slide_in_left, R.anim.slide_in_left);
                break;

            case R.id.iv_back://返回

                finish();
                break;

            case R.id.btn_submit_order://提交订单

                if (tvAddress.getText().toString().equals("")) {
                    ToastUtils.showMessageShort(this, "请选择收货地址");
                } else {

                    submitOrder();

                }
                break;
        }
    }


    /**
     * 提交订单
     */
    private void submitOrder() {


        List<OrderdModel.ShopListBean> shopLists = new ArrayList<>();
        List<OrderdModel.ShopListBean.ItemListBean> itemLists = new ArrayList<>();

        OrderdModel model = new OrderdModel();
        model.setReceiver(name);
        model.setAddress(address);
        model.setPhone(phone);
        model.setMobilephone(phone);
        model.setRemark(remark + "");
        model.setSendfree(sendfree);
        model.setState(0);
        model.setUlng(longitude + "");
        model.setUlat(latitude + "");
        model.setUserID(userId);
        model.setBid("0");
        model.setPayMode("1");
        model.setOrdersource("2");
        model.setSendfree("");
        model.setSendtype("1");
        model.setGainTime(currentTime);
        model.setIsuercard("0");
        model.setTogoId(shopId);

        OrderdModel.ShopListBean shopList = new OrderdModel.ShopListBean();
        for (int i = 0; i < 1; i++) {
            //商家id
            shopList.setTogoId(shopId);
            shopList.setLat(latitude + "");
            shopList.setLng(longitude + "");
            for (int j = 0; j < goodsBeans.size(); j++) {
                OrderdModel.ShopListBean.ItemListBean itemList = new OrderdModel.ShopListBean.ItemListBean();
                itemList.setOwername("0.0");//打包费
                itemList.setReveInt1("0");
                itemList.setReveInt2("0");
                itemList.setAddprice("0.0");
                itemList.setMaterial("0");
                itemList.setSid(goodsBeans.get(j).getGoodsId() + "");
                itemList.setSname("分");
                itemList.setPId(goodsBeans.get(j).getGoodsId() + "");
                itemList.setPName(goodsBeans.get(j).getGoodsName());
                itemList.setPPrice(goodsBeans.get(j).getGoodsPrice());
                itemList.setCurrentprice(goodsBeans.get(j).getGoodsPrice());
                itemList.setPNum(goodsBeans.get(j).getGoodsNum());
                itemList.setTogoId(shopId);
                itemLists.add(itemList);
            }
            shopList.setItemList(itemLists);
            shopLists.add(shopList);
        }
        model.setShopList(shopLists);

        String s = JSON.toJSONString(model, true);

        String url = Contents.SUBMIT_ORDER;

        RequestBody params = new FormBody.Builder().add("ordermodel", "[" + s + "]").build();

        Request request = new Request.Builder().url(url).post(params).build();

        Contents.okhttp.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String s = response.body().string();

                orderData = JSON.parseObject(s, OrderData.class);
                String orderId = orderData.getOrderid();
                int state = orderData.getOrderstate();
                mms = orderData.getMsg();

                if (state == 1) {
                    payOrderId(orderId);
                } else if (state == -1) {
                    handler.sendEmptyMessage(1);
                }

            }
        });
    }

    private String mms;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Toast.makeText(OrderActivity.this, mms + "", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    /**
     * 生成支付编号(订单编号+001
     *
     * @param orderId
     */
    private void payOrderId(String orderId) {


        String url = Contents.PAY_ORDERID_URL;

        RequestParams params = new RequestParams(url);
        params.addBodyParameter("orderid", orderId);
        params.addBodyParameter("price", priceAll + "");

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {

                    JSONObject object = new JSONObject(result);

                    int state = object.getInt("state");
                    if (state == 1) {

                        //根据orderId生成的支付编号
                        String orderid = object.getString("batch");

                        Intent payOrder = new Intent(OrderActivity.this, PayOrderActivity.class);
                        payOrder.putExtra("shopName", shopName);//商家名
                        payOrder.putExtra("shopImage", shopImage);//商家图片
                        payOrder.putExtra("orderId", orderid);//订单Id
                        payOrder.putExtra("priceAll", priceAll + "");//总价
                        startActivity(payOrder);
                    } else {
                        Toast.makeText(OrderActivity.this, "支付宝订单生成失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {


            case SELECT_ADDRESS://选择地址

                if (resultCode == Activity.RESULT_OK) {

                    name = data.getStringExtra("name");
                    address = data.getStringExtra("address");
                    phone = data.getStringExtra("phone");

                    tvName.setText(name);//收货人名
                    tvPhone.setText(phone);//电话
                    tvAddress.setText(address);//地址

                    //隐藏选择地址提示语
                    tvPleaseSelectAddress.setVisibility(View.INVISIBLE);
                }

                break;

            case REMARK://备注

                if (resultCode == Activity.RESULT_OK) {
                    remark = data.getStringExtra("remark");
                    tvRemark.setText(remark);//设置备注
                }
                break;


        }
    }
}
